<?php
namespace Home\Controller;
use Think\Controller;
require_once 'Qiniu/autoload.php';
use \Qiniu\Auth;
use \Qiniu\Storage\UploadManager;
use \Qiniu\Processing\PersistentFop;

class PushController extends controller {
    protected static $apiUrl = 'http://mobile.appwuhan.com/helper/';
    private $token = '';
    private $rotate = 0;

    public function getToken() {
        if(time()>=$this->expired_time){
            $authUrl = self::$apiUrl . 'auth.php';

            $data['username'] = 'phptest';
            $data['password'] = '123456';
            $info = gethttpcurl(urldecode($authUrl."?".http_build_query($data)."&t=".time()));
            $json = json_decode($info, true);
            $this->expired_time = $json[0]['expired_time'];
            $this->token = $json[0]['token'];
        }
        
        //print_r($info);
    }

    public function pushArticle($articleId) {
        $articleId = $articleId;// I('get.articleId', 0);
        $indexpic   =   null;
        $b=true;
        $info = M('Article')->alias('ar')
            ->join('__USER_INFO__ ui ON ar.user_id=ui.uid')
            ->where(array('id' => $articleId))->find();
        if(!$info) {
            $message['resultCode'] = 1;
            $message['message'] = '文章不存在';
            $this->ajaxReturn($message);
        }

        $info['content'] = $info['html_content'] ? $info['html_content'] : $info['content'];
        if(!$info['content']) {
            $message['resultCode'] = 1;
            $message['message'] = '文稿内容为空';
            $this->ajaxReturn($message);
        }

//        $fileList = M('Attachment')->where(array('aid' => $articleId,'attachstate'=>'1'))->order('sort ASC')->select(); // 文件列表

        $info['content'] = htmlspecialchars_decode($info['content']);

        $image_list = array();
        // 筛选出已使用的图片
        if(preg_match_all('/<img data-type="image"(.*?)id="(.*?)" src="(.*?)"/', $info['content'], $img_matchs)) {
            // 将图片的路径过滤出来
            if(!empty($img_matchs[2])) {
                foreach($img_matchs[2] as $k => $v) {
                    $attach_info = M('Attachment')->where(array('attachid' => $v))->find();
                    $image_list[$k] = $attach_info;
                }
            }
        }

        $video_list = array();
        // 筛选出已使用的音频
        if(preg_match_all('/data-videoid="(.*?)"/', $info['content'], $video_matchs)) {
            if(!empty($video_matchs[1])) {
                foreach($video_matchs[1] as $k => $v) {
                    $attach_info = M('Attachment')->where(array('attachid' => $v))->find();
                    $video_list[$k] = $attach_info;
                }
            }
        }


        $fileList = array_merge($image_list, $video_list);

        // print_r($fileList);exit;

        $this->getToken();//获取M2O的账户
        if(!$this->token){
            $message['resultCode'] = -1;
            $message['message'] = 'no token22';
            $this->ajaxReturn($message);
            exit();
        }

        $picids=array();

        /*foreach($fileList as $key=>$val) {
            $file=$val['filepath'] . $val['filename'];
            $temp=explode('.',$file);
            if(in_array($temp[count($temp)-1],array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb','mp4', 'mov'))){
                $dd=gethttpcurl("http://resource.local.appwuhan:".C('HOST_PORT')."/Mapi/Article/pushM2oVideo?token={$this->token}&file={$file}&title={$info['title']}",array('timeout'=>9999));

                $dd = json_decode(trim($dd, "\xEF\xBB\xBF"),true);
                $dd = isset($dd[0])?$dd[0]:$dd;
                $vids[$val['attachid']] = $dd;

            }else{
                $output=gethttpcurl("http://resource.local.appwuhan:".C('HOST_PORT')."/Mapi/Article/pushM2oAttchment?token={$this->token}&file={$file}",array('timeout'=>9999));
                $output = json_decode(trim($output, "\xEF\xBB\xBF"),true);
                $ids[$val['attachid']] = isset($output[0])?$output[0]:$output;
                $picids[]=$ids[$val['attachid']]['id'].'';
                if($b){
                    $indexpic = $ids[$val['attachid']]['id'];
                    $b=false;
                }
            }
        }*/

        foreach($fileList as $key=>$val) {
            if($val['client_attach_id']){
                //七牛云OSS文件处理
                $file=$val['filepath'] . $val['filename'];
                $fileLocal = gethttpcurl("http://resource.local.appwuhan:".C('HOST_PORT')."/Mapi/Article/genTempFile?file=" . $file . '&type=' . $val['type'] . '&ext=' . $val['ext'],array('timeout'=>9999));
                $fileLocal = trim($fileLocal, "\xEF\xBB\xBF");
                if(in_array($val['type'],array('video', 'audio'))){
                    $dd=gethttpcurl("http://resource.local.appwuhan:".C('HOST_PORT')."/Mapi/Article/pushM2oVideo?token={$this->token}&file={$fileLocal}&title={$info['title']}",array('timeout'=>9999));
                    $dd = json_decode(trim($dd, "\xEF\xBB\xBF"),true);
                    $dd = isset($dd[0])?$dd[0]:$dd;
                    $vids[$val['attachid']] = $dd;

                }else{
                    $output=gethttpcurl("http://resource.local.appwuhan:".C('HOST_PORT')."/Mapi/Article/pushM2oAttchment?token={$this->token}&file={$fileLocal}",array('timeout'=>9999));
                    $output = json_decode(trim($output, "\xEF\xBB\xBF"),true);
                    $ids[$val['attachid']] = isset($output[0])?$output[0]:$output;
                    $picids[]=$ids[$val['attachid']]['id'].'';
                    if($b){
                        $indexpic = $ids[$val['attachid']]['id'];
                        $b=false;
                    }
                }
            }else{
                //本地资源处理
                $file=$val['filepath'] . $val['filename'];
                $temp=explode('.',$file);
                if(in_array($temp[count($temp)-1],array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb','mp4', 'mov'))){
                    $dd=gethttpcurl("http://resource.local.appwuhan:".C('HOST_PORT')."/Mapi/Article/pushM2oVideo?token={$this->token}&file={$file}&title={$info['title']}",array('timeout'=>9999));

                    $dd = json_decode(trim($dd, "\xEF\xBB\xBF"),true);
                    $dd = isset($dd[0])?$dd[0]:$dd;
                    $vids[$val['attachid']] = $dd;

                }else{
                    $output=gethttpcurl("http://resource.local.appwuhan:".C('HOST_PORT')."/Mapi/Article/pushM2oAttchment?token={$this->token}&file={$file}",array('timeout'=>9999));
                    $output = json_decode(trim($output, "\xEF\xBB\xBF"),true);
                    $ids[$val['attachid']] = isset($output[0])?$output[0]:$output;
                    $picids[]=$ids[$val['attachid']]['id'].'';
                    if($b){
                        $indexpic = $ids[$val['attachid']]['id'];
                        $b=false;
                    }
                }
            }
        }

        /*v2.1.0
        foreach($ids as $val) {
             $info['content'] = '<img imageid="' . $val['id'] . '" src="' . $val['path'] . $val['dir'] . $val['filename'] . '" />' . $info['content'];
        }*/


        //v2.1.1 - start   修改为：推送M2O后台图片正序
        $m2oimg='';
//        foreach($ids as $val) {
//            $info['content'].='<img imageid="' . $val['id'] . '" src="' . $val['path'] . $val['dir'] . $val['filename'] . '" />';
//        }

        // 替换content中的图片地址

//        print_r($ids);
//        print_r($vids);
//        exit;


        foreach($ids as $key => $val) {
            if(preg_match('/<img([^<>]*?)?id="' . $key . '"([^<>]*?)>/i', $info['content'], $match)) {
                $info['content'] = preg_replace('/<img([^<>]*?)id="' . $key . '"([^<>]*?)>/i', '<img imageid="' . $val['id'] . '" src="' . $val['path'] . $val['dir'] . $val['filename'] . '" />', $info['content']);
            }
        }


        // 视频
//        foreach($vids as $key => $val) {
//            if(preg_match('/video=' . $key . '/i', $info['content'], $match)) {
//                $info['content'] = preg_replace('/video=' . $key . '/i', 'video=' . $val['id'], $info['content']);
//            }
//        }
//        print_r($vids);

        foreach($vids as $key => $val) {
            if(preg_match('/<img([^<>]*?)data\-videoid="' . $key . '"([^<>]*?)>/i', $info['content'], $match)) {
                $info['content'] = preg_replace('/<img([^<>]*?)data\-videoid="' . $key . '"([^<>]*?)>/i', '<img class="image-refer" src="http://img.appwuhan.com/material/sketch_map/livmedia/livmedia/vod_' . $val['id'] . '.png"/>', $info['content']);
                $info['content'] = str_replace(array('<p id="videobg">','<p id="audiobg">'), '<p style="text-align: center">', $info['content']);
            }
        }

       // print_r($info['content']);exit;

//        echo $info['content'];exit;
        //v2.1.1 -end

        /*v2.1.0
        $article['title'] = $info['title'];
        */

        //v2.1.1 - start   修改为：有视频的话，标题加 [带视频]
        if(isset($dd['return']) && $dd['return']=='success'){ //$dd为视频上传m2o的返回
            $article['title'] = '[带视频]'.$info['title'];
            if($b){

                $indexpic = null;
                $b=false;
            }
        }else{
            $article['title'] = $info['title'];
        }
        //v2.1.1 -end

        $article['subtitle'] =  $info['subtitle'];
        $article['keywords'] = $info['keywords'];
        $ulist=M('UserInfo')->where(array('uid'=>array('in',$info['author'])))->select();
        $author=array();
        foreach ($ulist as $key => $value) {
            $author[]=$value['realname'];
        }
        $author2=implode(',', $author);
        if(!in_array($info['realname'],$author)){
            $author2=$info['realname'].','.$author2;
        }

        $article['author'] = $author2;
        $article['brief'] = $info['brief'];
        $article['content'] = $info['content'];
        $article['indexpic'] = $indexpic;
        $article['column_id'] = '135';
        $article['access_token'] = $this->token;
        $article['material_id'] = implode(",",array_reverse($picids));

        $arts = gethttpcurl(self::$apiUrl . 'createContent.php', array('postarr' => $article));
        $arts = json_decode($arts, true);
        if($arts) {
            $message['resultCode'] = 0;
            $message['message'] = '';
            $message['fileList'] = $arts;
        } else {
            $message['resultCode'] = 1;
            $message['message'] = '推送失败';
        }

        // $this->ajaxReturn($message);
        return $message;
    }

    function pp($articleId){
        sock_get('http://localhost/Mapi/push/pushArticle.html',array('articleId'=>$articleId));
    }



/*    public function callback() {
        $notifyBody = file_get_contents('php://input');
        $notifyBody = trim(urldecode($notifyBody), "\"");
        $info = json_decode($notifyBody, true);
//        $this->ajaxReturn($info);
        if($info) {

            $dataGet['filename'] = $info['fkey'];
            $dataGet['filetype'] = $info['mimeType'];

            if($info['avinfo']['video']) {
                $uptype = 'video';
                $dataGet['oriwidth'] = $info['avinfo'][$uptype]['width'];
                $dataGet['oriheight'] = $info['avinfo'][$uptype]['height'];
                $dataGet['thumb'] = C('QINIU_RESOURCE_HOST'). $info['fkey'] . '?vframe/jpg/offset/10/w/' . $info['avinfo'][$uptype]['width'] . '/h/' . $info['avinfo'][$uptype]['height'];
            }

            $dataGet['filesize'] = formatBytes($info['fsize']);
            $dataGet['filepath'] = C('QINIU_RESOURCE_HOST');

            $dataGet['uploadtime'] = time();
            $dataGet['aid'] = $info['aid'];
            $dataGet['sort'] = $info['desc'];
            $dataGet['ip'] = I('server.HTTP_X_REAL_IP');
            $dataGet['type'] = strtolower($info['type']);

            $res = M('Attachment')->add($dataGet);
            if(!$res) {
                $message['resultCode'] = 1;
                $message['message'] = '上传失败，请重试';
            } else {
                M('Attachment')->where(array('attachid' => $res))->save(array('aid' => $info['aid']));
                switch(ucfirst($info['type'])){
                    case "Image":
                        M('Article')->where('id = ' . $info['aid'] . ' AND indexpic = ""')->save(array('indexpic' => $dataGet['thumb']));
                        break;
                    case "Video":
                        M('Article')->where('id = ' . $info['aid'] )->save(array('indexpic' => $dataGet['thumb']));
                        break;
                        break;
                }
                $message['resultCode'] = 0;
                $message['message'] = '';
                $message['attachid'] = $res;
                $message['articleid'] = $info['aid'];
                $message['type'] = strtolower($info['type']);
                $message['path'] = $dataGet['thumb'];
                $message['fullpath'] = $dataGet['filepath'] . $dataGet['filename'];
            }
        } else {
            $message['resultCode'] = 1;
            $message['message'] = '服务器错误';
        }

        $this->ajaxReturn($message);
    }*/


    public function callback() {
        $notifyBody = file_get_contents('php://input');
        $notifyBody = trim(urldecode($notifyBody), "\"");
        $info = json_decode($notifyBody, true);

        //$this->ajaxReturn($info);
        if($info) {

            $dataGet['filename'] = $info['hash'];
            $dataGet['filepath']=str_replace($info['hash'],"",$info['fkey']);
            $dataGet['filetype'] = $info['mimeType'];

            if(isset($info['avinfo']['video'])) {
                $dataGet['type']="video";

                if(!isset($info['avinfo']['video']['tags']['rotate']) || $info['avinfo']['video']['tags']['rotate']==0 || $info['avinfo']['video']['tags']['rotate']==180){
                    $dataGet['oriwidth']=$info['avinfo']['video']['width'];
                    $dataGet['oriheight']=$info['avinfo']['video']['height'];
                }elseif($info['avinfo']['video']['tags']['rotate']==90 || $info['avinfo']['video']['tags']['rotate']==270){
                    $dataGet['oriwidth']=$info['avinfo']['video']['height'];
                    $dataGet['oriheight']=$info['avinfo']['video']['width'];
                }


            } elseif(isset($info['avinfo']['audio'])) {
                $dataGet['type']="audio";
                $dataGet['audiosecondcount']=round($info['avinfo']['format']['duration']);
            }

            $dataGet['filesize'] = formatBytes($info['fsize']);
            $dataGet['uploadtime'] = time();
            $dataGet['aid'] = $info['aid'];
            $dataGet['sort'] = $info['desc'];
            $dataGet['ip'] = I('server.HTTP_X_REAL_IP');
//            $dataGet['type'] = strtolower($info['type']);
            $dataGet['ext'] = $info['ext'];
            $dataGet['client_attach_id'] = 'qiniu-' . time() .'-'. mt_rand(0, 999999999); // 标识是走七牛云上传的

            $attachid = M('Attachment')->add($dataGet);
            if(!$attachid) {
                $message['resultCode'] = 1;
                $message['message'] = '上传失败，请重试';
            } else {

                $res = $this->vframeQiniu($dataGet['filepath'] . $dataGet['filename'],$dataGet['oriwidth'],$dataGet['oriheight'],$attachid);
//                $this->ajaxReturn($info);
                $message['resultCode'] = 0;
                $message['message'] = '';
                $message['attachid'] = $attachid;
                $message['articleid'] = $info['aid'];
                $message['type'] = strtolower($info['type']);
                $message['path'] = C('QINIU_RESOURCE_HOST') . $dataGet['filepath'] . $dataGet['filename'] . '?vframe/jpg/offset/1/w/' . $dataGet['oriwidth'] . '/h/' . $dataGet['oriheight'];
                $message['fullpath'] = $dataGet['filepath'] . $dataGet['filename'];
            }
        } else {
            $message['resultCode'] = 1;
            $message['message'] = '服务器错误';
        }

        $this->ajaxReturn($message);
    }

    public function vframeQiniu($key,$w,$h,$attachid){
        $accessKey = C('QINIU_AK');
        $secretKey = C('QINIU_SK');
        $bucket = C('QINIU_VIDEO_BUCKET');
        $auth = new Auth($accessKey, $secretKey);
        //转码是使用的队列名称。 https://portal.qiniu.com/mps/pipeline
        $pipeline = 'C3DQg0Yz';
        //转码完成后通知到你的业务服务器。
        $notifyUrl = "http://".I("server.HTTP_HOST").'/Home/Push/setQiniuVideoThumb/attachid/'.$attachid;
        $force = false;

        $config = new \Qiniu\Config();
        $config->useHTTPS = true;
        $pfop = new PersistentFop($auth, $config);

        //要进行视频截图操作
        //$h=round($h*680/$w);
        //$fops = "vframe/jpg/offset/1/w/345/h/".$h."|saveas/" .\Qiniu\base64_urlSafeEncode($bucket . ":".$key.".jpg");
        $h=round($h*345/$w);
        $fops = "vframe/jpg/offset/1/w/345/h/".$h."|saveas/" .\Qiniu\base64_urlSafeEncode($bucket . ":".$key.".jpg");
        M('Attachment')->where(array('attachid'=>$attachid))->save(array('thumbwidth'=>345,'thumbheight'=>$h));
        list($id, $err) = $pfop->execute($bucket, $key, $fops, $pipeline, $notifyUrl, $force);

        if($err != null) {
            return array('success' => false);
        } else {
            return array('success' => true);
        }
    }

    public function setQiniuVideoThumb($attachid){
        apigetpost();
        $key=I("post.");
        file_put_contents('a.txt',json_encode($key));
        \Think\Log::record($key['code'],'WARN',true);
        if($key['code'].""==="0"){
            M('Attachment')->where(array('attachid'=>$attachid))->save(array('thumb'=>$key['inputKey'].".jpg"));
        }


    }
}